package com.ethan.auth.extention;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ethan.enums.BizCodeEnum;
import com.ethan.enums.Constant;
import com.ethan.excetion.BizException;
import com.ethan.mapper.SysUserMapper;
import com.ethan.model.LoginUser;
import com.ethan.model.SysUserDO;
import com.ethan.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: TODO
 * @Author ethan
 * @CreateDate:2022/3/17 15:38
 * @UpdateDate: 2021/6/17 08:52
 * @Version 1.0
 */
@Service
@Slf4j
public class UserDetailServceImpl implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUserDO sysUserDO = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUserDO>().eq(SysUserDO::getUsername,s));
        if (sysUserDO==null){
            throw new BizException(BizCodeEnum.ACCOUNT_PWD_ERROR);
        }
        LoginUser loginUser = new LoginUser();
        loginUser.setId(sysUserDO.getUserId());
        loginUser.setName(sysUserDO.getUsername());
        loginUser.setPwd(sysUserDO.getPassword());
        List<String> auths = sysUserMapper.selectAuthById(sysUserDO.getUserId());
        loginUser.setAuths(auths);
        redisUtil.set(String.format(Constant.CACHE_USER_TOKEN,sysUserDO.getUserId()+""),loginUser);
        loginUser.setAuths(null);
        return loginUser;
    }

}
